package com.graduationproject.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.graduationproject.common.R;
import com.graduationproject.entity.PageResult;
import com.graduationproject.entity.RelRolePerm;
import com.graduationproject.entity.RelUserRole;
import com.graduationproject.entity.Role;
import com.graduationproject.service.IRoleService;
import com.graduationproject.service.Impl.RelRolePermServiceImpl;
import com.graduationproject.service.Impl.RelUserRoleServiceImpl;
import com.graduationproject.service.Impl.RoleServiceImpl;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-08-20
 */
@RestController
@RequestMapping("api/role")
public class RoleController {
    @Autowired
    private RoleServiceImpl roleService;

    @Autowired
    private RelRolePermServiceImpl relRolePermService;

    @Autowired
    private RelUserRoleServiceImpl relUserRoleService;

    @GetMapping("/getRole")
    public R getRole(String pageNow, String pageSize) {
        PageHelper.startPage(Integer.parseInt(pageNow), Integer.parseInt(pageSize)); // 开始分页
        List<Role> list = roleService.list();
        PageResult<Role> rolePageResult = new PageResult<>(list);
        return R.success(rolePageResult);
    }

    @PostMapping("/addRole")
    public R addRole(@RequestBody Role role){
        if(role.getRoleName() == null) {
            throw new RuntimeException("角色名称为空");
        }
        boolean save = roleService.save(role);
        if(save) {
            String permission = "1,2,3,4,5,6";
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("role_name", role.getRoleName());
            Role one = roleService.getOne(roleQueryWrapper);
            RelRolePerm relRolePerm = new RelRolePerm();
            relRolePerm.setRoleId(one.getId());
            relRolePerm.setPermissionId(permission);
            relRolePermService.save(relRolePerm);
            return R.success("添加成功");
        }else {
            return R.error("添加失败");
        }
    }

    @DeleteMapping("/deleteRole/{id}")
    public R deleteRole(@PathVariable Integer id) {
        if(id < 0) {
            throw new RuntimeException("系统错误");
        }
        Role byId = roleService.getById(id);
        QueryWrapper<RelUserRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("role_id", byId.getId());
        List<RelUserRole> list = relUserRoleService.list(roleQueryWrapper);
        if(list != null || list.size() > 0) {
            return R.error("当前角色已经关联用户");
        }
        roleService.removeById(byId);
        return R.success("删除成功");
    }
}
